<template>
  <!-- 道具属性面板 -->
  <div class="relative h-full overflow-hidden border border-gray-500">
    <!-- 浮动窗口样式颜色表面板 - 可拖动 -->
    <div 
      v-if="colorTablePanelVisible" 
      class="fixed w-64 max-h-[70vh] bg-black text-white border border-gray-500 rounded shadow-xl z-30 flex flex-col"
      :style="{ left: `${windowPosition.x}px`, top: `${windowPosition.y}px` }"
    >
      <!-- 可拖动的标题栏 -->
      <div class="p-2 border-b border-gray-500 cursor-move hover:bg-gray-900 flex justify-between items-start" @mousedown="startDrag">
        <div>
          <h3 class="font-bold">暗黑2颜色代码表</h3>
          <span class="text-sm">窗口可拖动;点击左边的颜色代码复制到剪贴板</span>
        </div>
        <button 
          @click.stop="colorTablePanelVisible = false"
          class="text-white hover:text-gray-300 bg-gray-800 hover:bg-gray-700 px-2 py-1 rounded border border-gray-600 ml-2 flex-shrink-0"
          title="关闭面板"
        >
          ×
        </button>
      </div>
      <div class="flex-1 p-2 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-700 scrollbar-track-gray-900">
        <table class="w-full border-collapse">
          <thead>
            <tr class="bg-gray-900">
              <th class="text-left py-1 text-xs">暗黑2颜色代码</th>
              <th class="text-left py-1 text-xs">颜色</th>
              <th class="text-left py-1 text-xs">备注</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="color in colorData" :key="color.d2Code" class="hover:bg-gray-900">
              <td class="py-1">
                <button 
                  class="font-mono text-sm bg-gray-800 hover:bg-gray-700 px-2 py-1 rounded border border-gray-600"
                  @click="copyToClipboard(color.d2Code)"
                >
                  {{ color.d2Code }}
                </button>
              </td>
              <td>
                <div 
                  :style="{ backgroundColor: color.htmlCode }"
                  class="w-6 h-6 border border-gray-600 inline-block"
                ></div>
              </td>
              <td class="text-xs text-gray-300">
                {{ color.remark }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 复制成功提示 - 位于颜色表底部 -->
      <div v-if="showCopyToast" class="bg-green-600 text-white px-2 py-1 text-sm text-center">
        {{ copiedCode }} 已经复制
      </div>
    </div>
    
    <!-- 物品详情面板 -->
    <div class="bg-slate-800 text-white p-4 h-full overflow-auto">
      <h3 class="text-lg font-bold mb-4 border-b border-gray-500 pb-2">物品详情</h3>
    <div v-if="workItem" class="space-y-3">
      <div class="flex items-center py-1">
        <span class="font-semibold text-gray-300">ID:</span>
        <span class="ml-2">{{ workItem.id }}</span>
      </div>
      <div class="flex items-center py-1">
        <span class="font-semibold text-gray-300">Key:</span>
        <span class="ml-2">{{ workItem.Key }}</span>
      </div>
      
      <div v-if="props.resourceItemName === 'item-names.json'" class="bg-black p-4 rounded-lg mb-4">
        <div class="flex justify-between items-center mb-2">
          <h3 class="text-white font-bold">物品详情</h3>
          <button 
            @click="enableItemDetails = !enableItemDetails" 
            class="text-white bg-gray-700 hover:bg-gray-600 px-2 py-1 rounded"
          >
            {{ enableItemDetails ? '关闭' : '显示' }}
          </button>
        </div>
        
        <div v-if="enableItemDetails">
          <div>级别:<span class="text-green-400"> {{ getItemLevel(workItem) }} </span></div>
          
          <div id='jump-to-other-levels' v-if="workItem.desc && [1,2,3].includes(workItem.desc.level)" class="my-3">
             <button 
               v-for="btnLevel in [1,2,3]" 
               :key="btnLevel" 
               @click="searchEquipOtherLevel(workItem.desc, btnLevel)"
               :disabled="btnLevel === workItem.desc.level"
               class="mr-2 px-2 py-1 bg-gray-700 hover:bg-gray-600 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-gray-500 disabled:hover:bg-gray-500"
             >
               ->{{ levelToLabelMap[btnLevel] || btnLevel }}
             </button>
          </div>
          <div>分类:<span class="text-blue-400"> {{getItemCategory(workItem)}} </span></div>
          <img v-if="workItem && workItem.desc" :src="`/images/items/${workItem.desc.imageName}.png`" :alt="workItem.desc.imageName" class="w-32 h-32 object-contain my-4" @error="handleItemImageError" />

          <div v-if="workItem.desc && workItem.desc.details" class="text-white">
            <div v-for="(line, index) in workItem.desc.details" :key="index" class="whitespace-pre-wrap">
              {{ line }}
            </div>
          </div>
        </div>
      </div>
     
      <div class="mt-4 space-y-3">
        <div class="flex items-center mb-3">
          <h4 class="text-md font-semibold text-gray-300 mr-2">语言选择：</h4>
          <select 
            v-model="selectedLanguage"
            class="bg-gray-800 text-white border border-gray-600 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option 
              v-for="option in languageOptions" 
              :key="option.value" 
              :value="option.value"
            >
              {{ option.label }}
            </option>
          </select>
        </div>
        
        <!-- 动态显示选中的语言文本 -->
        <div class="mb-2">
          <div class="font-semibold text-blue-400 mb-1">{{ getCurrentLanguageLabel() }}</div>
          <div class="p-2 bg-gray-900 rounded min-h-6 text-center">
            <D2TextBox 
:text="String(workItem[selectedLanguage as keyof typeof workItem] ?? '')"
              :key-prefix="`detail-${selectedLanguage}-${workItem.id}`" 
            />
          </div>
          <span class="text-sm text-gray-400">编辑原始文本，注意行号是倒序的：</span>
          <textarea 
            v-model="workItem[selectedLanguage as keyof D2ItemStringToDisplay] as string"
            class="w-full p-2 mt-2 bg-gray-800 text-white rounded border border-gray-600 text-left whitespace-nowrap overflow-y-hidden min-h-0"
            :rows="String(workItem[selectedLanguage as keyof D2ItemStringToDisplay] || '').split('\n').length +1|| 1"
            :onkeyup="onD2TextChange(selectedLanguage as keyof D2ItemStringToDisplay)"
          ></textarea>
          <div class="flex justify-between items-center mt-2">
            <button
              class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
              @click="toggleColorTablePanel"
            >
              颜色表
            </button>
            <button
              class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 disabled:bg-gray-500 disabled:cursor-not-allowed"
              @click="saveItem"
              :disabled="!unsavedChange"
            >
              保存
            </button>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="flex justify-center items-center h-25">
      <p class="text-gray-400 italic">请选择一个物品查看详情</p>

    </div>
  </div>
  

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { D2ItemStringToDisplay } from './types';
import D2TextBox from './D2TextBox.vue';
import { tableColor, specColors, equipSubCategoryLabels } from '../common/appContext.json';
const enableItemDetails = ref<boolean>(true);

const levelToLabelMap:{[key:number]:string}={
  0:'其他',
  1:'普通',
  2:'扩展',
  3:'精华'
}
// 定义组件属性
const props = defineProps<{
  item?: D2ItemStringToDisplay;
  resourceItemName?:string
}>();

// 当前选中的语言，默认简体中文
const selectedLanguage = ref<string>('zhCN');

// 语言选项配置
const languageOptions = [
  { value: 'zhCN', label: '中文（简体）' },
  { value: 'zhTW', label: '中文（繁体）' },
  { value: 'enUS', label: '英文（美国）' }
];

// 获取当前选中语言的显示标签
const getCurrentLanguageLabel = () => {
  const option = languageOptions.find(opt => opt.value === selectedLanguage.value);
  return option ? option.label : '未知语言';
};



// 获取物品级别文本
const getItemLevel = (item?: D2ItemStringToDisplay): string => {
  if (!item || !item.desc || item.desc.level === undefined) return '未知';
  
  const desc = item.desc;
  //console.log(itemData);
  if (!desc || desc.level === undefined) return '未知';
  return levelToLabelMap[desc.level] || '未知';
  
};



//当物品的图片找不到时候会替换为问号图片
const handleItemImageError = ($event: Event) => {
  if ($event.target) {
    const imgElement = $event.target as HTMLImageElement;
    // 防止无限循环，如果已经是默认图片则不再处理
    if (imgElement.src.indexOf('unknown.jpg') === -1) {
      imgElement.src = '/images/items/unknown.jpg';
    }
  }
};



const mainCategoryMap:{[key:string]:string} =
  {
    'weapon': '武器',
    'armor': '护甲',
    'misc': '杂项'
  }
const getItemCategory = (item?: D2ItemStringToDisplay): string => {
  if (!item || !item.desc || !item.desc.mainCateg || !item.desc.subCateg) return '未知';
  const mainCategory = mainCategoryMap[item.desc.mainCateg ] || '其他';
  const subCategory = (equipSubCategoryLabels as {[key:string]:string})[item.desc.subCateg ] || '其他';
  return `${mainCategory}:${subCategory}`;
}

import { D2ItemDesc } from './types';

// 定义并获取emit函数,这个函数在主组件ContentPanel.vue中被鉴定并绑定方法
const emit = defineEmits<{
  'searchSpecLevelItem': [data: {imageName: string, level: number}]
  'saveItemEdit': [data: D2ItemStringToDisplay]
}>();

const searchEquipOtherLevel=(itemDesc:D2ItemDesc,level:number)=>{
  // 参数验证
  if (!itemDesc || !itemDesc.imageName || !level || level < 1 || level > 3) {
    console.error('searchEquipOtherLevel: 无效的跳转参数', itemDesc, level);
    return;
  }
  
  // 直接使用原始imageName和目标level，不做处理
  emit('searchSpecLevelItem', {
    imageName: itemDesc.imageName,
    level: level
  });
}

//对物品的文本编辑功能.当主面板选择的物品发生变化时，生成一个副本
const sourceItem = ref<D2ItemStringToDisplay|undefined>(undefined);//相当于oldObj
const workItem = ref<D2ItemStringToDisplay|undefined>(undefined);
const unsavedChange = ref<boolean>(false);

watch(()=>props.item, async (newObj) => {
    if (newObj){
          //如果点选了同一个物体，那么编辑状态不会重置
        if (workItem.value && newObj && newObj?.Key === workItem.value.Key) {
             return;
        } else if (unsavedChange.value) {
          // 使用安全的方式引用sourceItem的Key，避免第一次更新时出错
          const currentItemKey = sourceItem.value?.Key || '未知';
          if (await confirm(`当前物品 ${currentItemKey} 有未保存的编辑，是否要更改？`)){
            saveItem();
          }
          // 无论用户是否选择保存，都需要更新sourceItem和workItem
          sourceItem.value = newObj;
          workItem.value = JSON.parse(JSON.stringify(newObj));
        } else {
          // 没有未保存更改，直接更新
          sourceItem.value = newObj;
          workItem.value = JSON.parse(JSON.stringify(newObj));
        }
    }
}, { immediate: true });

const saveItem=()=>{
  if(!sourceItem.value){
    return;
  }
  if(!workItem.value){
    return;
  }
  if (workItem.value?.Key !== sourceItem.value?.Key){
    return;
  }
  sourceItem.value.zhCN = workItem.value.zhCN;
  sourceItem.value.zhTW = workItem.value.zhTW;
  sourceItem.value.enUS = workItem.value.enUS;
  unsavedChange.value = false;
  emit('saveItemEdit', sourceItem.value);
}

const onD2TextChange = (propName: keyof D2ItemStringToDisplay) => {
  if (!workItem.value) return;
  const rawText = props.item?.[propName] || '';
  unsavedChange.value = (workItem.value[propName as keyof D2ItemStringToDisplay] as string) !== rawText;
};

//--- 颜色表面板相关功能开始 ---
const colorTablePanelVisible = ref<boolean>(false);
const showCopyToast = ref<boolean>(false);
const copiedCode = ref<string>('');

// 窗口位置和拖动状态
const windowPosition = reactive({
  x: 20,
  y: 10
});
const isDragging = ref<boolean>(false);
const dragOffset = reactive({
  x: 0,
  y: 0
});

// 开始拖动
const startDrag = (event: MouseEvent) => {
  isDragging.value = true;
  // 计算鼠标相对于窗口左上角的偏移量
  const windowElement = (event.currentTarget as HTMLElement).parentElement;
  if (windowElement) {
    const rect = windowElement.getBoundingClientRect();
    dragOffset.x = event.clientX - rect.left;
    dragOffset.y = event.clientY - rect.top;
  }
  
  // 添加鼠标事件监听器
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
};

// 拖动中
const onDrag = (event: MouseEvent) => {
  if (isDragging.value) {
    // 更新窗口位置，减去偏移量确保鼠标位置不变
    windowPosition.x = event.clientX - dragOffset.x;
    windowPosition.y = event.clientY - dragOffset.y;
  }
};

// 停止拖动
const stopDrag = () => {
  isDragging.value = false;
  // 移除事件监听器
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

const toggleColorTablePanel = () => {
  colorTablePanelVisible.value = !colorTablePanelVisible.value;
};

// 将颜色数据转换为数组以便在表格中显示
const colorData = ref(Object.entries(tableColor).map(([d2Code, htmlCode]) => ({
  d2Code,
  htmlCode,
  remark: (specColors as Record<string, string>)[d2Code] || ''
})));



// 复制到剪贴板功能
const copyToClipboard = async (code: string) => {
  try {
    await navigator.clipboard.writeText(code);
    copiedCode.value = code;
    showCopyToast.value = true;
    // 2秒后自动隐藏提示
    setTimeout(() => {
      showCopyToast.value = false;
    }, 2000);
  } catch (err) {
    console.error('复制失败:', err);
  }
};
//--- 颜色表面板相关功能结束 ---

</script>

<style scoped>
/* 已使用Tailwind CSS替代原生样式 */
.scrollbar-thin {
  scrollbar-width: thin;
}

.scrollbar-thumb-gray-700::-webkit-scrollbar-thumb {
  background-color: #4b5563; /* gray-700 */
  border-radius: 9999px;
}

.scrollbar-track-gray-900::-webkit-scrollbar-track {
  background-color: #111827; /* gray-900 */
  border-radius: 9999px;
}

.scrollbar-thin::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
</style>